<template>
  <div class="min-h-screen bg-gray-50">
    <UpdateBoardModal
      v-model="showUpdateModal"
      :board-id="board?.id"
      :board-data="board"
      @updated="fetchBoardDetail"
    />
    <ImageViewer
      v-model="showImageViewer"
      :image="selectedImage"
    />
    <!-- 删除确认对话框 -->
    <UModal v-model="showDeleteConfirm">
      <div class="p-6">
        <div class="flex items-center gap-4 mb-4">
          <UIcon name="i-heroicons-exclamation-triangle" class="text-red-500 h-8 w-8" />
          <h3 class="text-lg font-medium">确认删除</h3>
        </div>
        <p class="text-gray-600 mb-6">确定要删除画板 "{{ board?.title }}" 吗？此操作不可恢复。</p>
        <div class="flex justify-end space-x-3">
          <UButton color="gray" variant="soft" @click="showDeleteConfirm = false">取消</UButton>
          <UButton color="red" :loading="deleteLoading" @click="deleteBoard">确认删除</UButton>
        </div>
      </div>
    </UModal>
    <!-- 加载状态 -->
    <div v-if="loading" class="flex justify-center items-center py-12">
      <UIcon name="i-heroicons-arrow-path" class="h-8 w-8 animate-spin text-primary-600" />
    </div>

    <div v-else-if="error" class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12 text-center">
      <UIcon name="i-heroicons-exclamation-circle" class="h-12 w-12 text-red-500 mx-auto mb-4" />
      <h2 class="text-xl font-medium text-gray-900 mb-2">{{ error }}</h2>
      <UButton color="primary" @click="fetchBoardDetail" class="mt-4">
        重试
      </UButton>
    </div>

    <div v-else-if="board">
      <!-- 返回按钮 -->
      <div class="bg-white shadow-sm">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
          <ULink to="/user/me" class="inline-flex items-center text-gray-600 hover:text-primary-600">
            <UIcon name="i-heroicons-arrow-left" class="h-5 w-5 mr-1" />
            <span>返回我的画板</span>
          </ULink>
        </div>
      </div>

      <!-- 画板标题和描述 -->
      <div class="bg-white border-b border-gray-200">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div class="flex items-start justify-between">
            <div>
              <h1 class="text-3xl font-bold text-gray-900 mb-4">{{ board.title }}</h1>
              <p class="text-gray-600 mb-4">{{ board.description }}</p>
              <div class="flex flex-wrap gap-2 mb-4">
                <UBadge v-for="tag in board.tags.split(',')" :key="tag" color="secondary" variant="subtle" size="md" class="inline-block">
                  <span class="text-gray-600">{{ tag.trim() }}</span>
                </UBadge>
              </div>
              <div class="flex items-center space-x-4 text-sm text-gray-500">
                <span class="flex items-center space-x-1">
                  <UIcon name="i-heroicons-fire" class="h-5 w-5 text-orange-500" />
                  <span>热度 {{ board.hotness }}</span>
                </span>
                <span class="flex items-center space-x-1">
                  <UIcon name="i-heroicons-photo" class="h-5 w-5" />
                  <span>{{ board.images.length }}张图片</span>
                </span>
              </div>
            </div>
            <div class="flex space-x-2">
              <UButton color="primary" icon="i-heroicons-pencil" variant="soft" @click="showUpdateModal = true">
                编辑画板
              </UButton>
              <UButton color="primary" icon="i-heroicons-share" variant="soft">
                分享画板
              </UButton>
              <UButton color="red" icon="i-heroicons-trash" variant="soft" @click="showDeleteConfirm = true">
                删除画板
              </UButton>
            </div>
          </div>
        </div>
      </div>

      <!-- 图片展示区域 -->
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div 
            v-for="image in board.images" 
            :key="image.id" 
            class="bg-white rounded-lg shadow-sm overflow-hidden hover:shadow-md transition-shadow duration-200"
          >
            <!-- 图片 -->
            <div class="relative aspect-w-4 aspect-h-3 cursor-pointer" @click="openImageViewer(image)">
              <NuxtImg 
                :src="image.img_url" 
                :alt="image.title" 
                class="object-cover w-full h-full" 
                loading="lazy" 
                placeholder 
                format="avif,webp" 
                quality="80"
                :modifiers="{
                  width: 800,
                  height: 600,
                  fit: 'cover',
                }"
              />
              <div class="absolute inset-0 bg-black opacity-0 hover:opacity-10 transition-opacity duration-300 flex items-center justify-center">
                <UIcon name="i-heroicons-magnifying-glass-plus" class="h-10 w-10 text-white opacity-0 group-hover:opacity-100" />
              </div>
            </div>
            
            <!-- 图片信息 -->
            <div class="p-4">
              <h3 class="text-lg font-medium text-gray-900 mb-2">{{ image.title }}</h3>
              <p class="text-sm text-gray-500 mb-4">{{ image.content }}</p>
              
              <!-- 交互按钮 -->
              <div class="flex items-center justify-between">
                <div class="flex items-center space-x-4">
                  <span class="flex items-center space-x-1 text-gray-500">
                    <UIcon name="i-heroicons-eye" class="h-5 w-5" />
                    <span>{{ image.views_count }}</span>
                  </span>
                  <span class="flex items-center space-x-1 text-gray-500">
                    <UIcon name="i-heroicons-arrow-down-tray" class="h-5 w-5" />
                    <span>{{ image.download_count }}</span>
                  </span>
                  <span class="flex items-center space-x-1 text-gray-500">
                    <UIcon name="i-heroicons-clock" class="h-5 w-5" />
                    <span>{{ formatDate(image.created_at) }}</span>
                  </span>
                </div>
                
                <UDropdown :items="getImageMenuItems(image)">
                  <UButton
                    color="gray"
                    variant="ghost"
                    icon="i-heroicons-ellipsis-horizontal"
                  />
                </UDropdown>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { api } from '~/utils/api'
import ImageViewer from '~/components/ImageViewer.vue'

interface Image {
  id: number
  title: string
  content: string
  user_id: number
  img_url: string
  views_count: number
  download_count: number
  created_at: number
}

interface Board {
  id: number
  title: string
  category_id: number
  tags: string
  status: number
  hotness: number
  flag: number
  description: string
  images: Image[]
}

const route = useRoute()
const boardId = route.params.id

const loading = ref(true)
const error = ref<string | null>(null)
const board = ref<Board | null>(null)
const showUpdateModal = ref(false)
const showImageViewer = ref(false)
const selectedImage = ref<Image | null>(null)
const showDeleteConfirm = ref(false)
const deleteLoading = ref(false)

// 打开图片预览
const openImageViewer = (image: Image) => {
  selectedImage.value = image
  showImageViewer.value = true
}

// 图片菜单项
const getImageMenuItems = (image: Image) => [
  [
    {
      label: '下载图片',
      icon: 'i-heroicons-arrow-down-tray',
      click: () => {
        const link = document.createElement('a')
        link.href = image.img_url
        link.download = image.title || 'image'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }
    },
    {
      label: '分享图片',
      icon: 'i-heroicons-share',
      click: () => console.log('分享图片')
    }
  ],
  [
    {
      label: '查看原图',
      icon: 'i-heroicons-photo',
      click: () => {
        // 直接使用传入的图片对象
        openImageViewer(image);
      }
    }
  ]
]

// 原来的静态菜单项定义可以删除
// const imageMenuItems = [
//   [
//     {
//       label: '下载图片',
//       icon: 'i-heroicons-arrow-down-tray',
//       click: (e: Event, item: any) => {
//         const link = document.createElement('a')
//         link.href = item.img_url
//         link.download = item.title || 'image'
//         document.body.appendChild(link)
//         link.click()
//         document.body.removeChild(link)
//       }
//     },
//     {
//       label: '分享图片',
//       icon: 'i-heroicons-share',
//       click: () => console.log('分享图片')
//     }
//   ],
//   [
//     {
//       label: '查看原图',
//       icon: 'i-heroicons-photo',
//       click: (e: Event, item: any) => {
//         // 从board.images中找到对应的图片对象
//         if (board.value && board.value.images && item) {
//           // 确保item存在并且有id属性
//           if (!item.id) {
//             console.error('图片项缺少ID:', item);
//             return;
//           }
//           
//           const imageId = item.id;
//           const foundImage = board.value.images.find(img => img.id === imageId);
//           if (foundImage) {
//             openImageViewer(foundImage);
//           } else {
//             console.error('未找到对应的图片:', imageId);
//           }
//         }
//       }
//     ]
//   ]
// ]

// 获取画板详情
// 格式化日期
const formatDate = (timestamp: number) => {
  if (!timestamp) return '暂无数据';
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

const fetchBoardDetail = async () => {
  try {
    loading.value = true
    error.value = null
    
    const response = await api.get(`/api/v1/boards/${boardId}`)
    const data = response
    
    if (data.code === 0) {
      board.value = data.data
    } else {
      error.value = data.msg || '获取画板详情失败'
    }
  } catch (e) {
    console.error('获取画板详情失败:', e)
    error.value = '网络请求错误，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 删除画板
const deleteBoard = async () => {
  try {
    deleteLoading.value = true
    
    const response = await api.delete(`/api/v1/boards/${boardId}`)
    
    if (response.code === 0) {
      // 显示成功提示
      useToast().add({
        title: '成功',
        description: '画板已删除',
        color: 'green',
        icon: 'i-heroicons-check-circle',
        timeout: 3000
      })
      
      // 跳转回我的画板页面
      navigateTo('/user/me')
    } else {
      // 显示错误信息
      console.error('删除画板失败:', response.msg)
    }
  } catch (error) {
    console.error('删除画板失败:', error)
  } finally {
    deleteLoading.value = false
    showDeleteConfirm.value = false
  }
}

onMounted(() => {
  fetchBoardDetail()
})
</script>

<!-- 添加更新画板模态框组件 -->
<UpdateBoardModal 
  v-model="showUpdateModal" 
  :board-id="boardId" 
  :board-data="board" 
  @updated="fetchBoardDetail" 
/>